<template>
  <vxe-modal
    resize
    esc-closable
    width="80%"
    height="97%"
    showFooter
    v-model="formVisible"
    :loading="formLoading"
    @hide="()=>{ $emit(`close`) }"
  >
    <template slot="title">
      <span>实体开发</span>
    </template>
    <template>
      <el-scrollbar class="scrollbar-handle">
        <!-- 步骤条 -->
        <el-steps :active="active" finish-status="success" simple>
          <el-step title="数据表选择"></el-step>
          <el-step title="信息配置"></el-step>
          <el-step title="代码预览"></el-step>
        </el-steps>
        <!-- 数据表选择 -->
        <div v-show="active === 0" class="step_div">
          <vxe-grid
            ref="mainTable"
            :toolbar="tableToolbar"
            :columns="tableColumn"
            :data="tableData"
            :expand-config="{ lazy: true, loadMethod: expanded }"
            row-id="name"
            :checkbox-config="{
              reserve: true,
              trigger: 'row',
              highlight: true,
            }"
            :sync-resize="formVisible"
          >
            <!-- 业务按钮 -->
            <template v-slot:toolbar_buttons></template>
            <!-- 快速查询 -->
            <template v-slot:toolbar_search>
              <rayd-quick-query v-model="filterName" @query="loadTables"></rayd-quick-query>
            </template>
            <!--  子表格模板 -->
            <template v-slot:subTable="{ row }">
              <vxe-grid
                :ref="`subTable` + row._XID"
                height="250"
                :columns="subTableColumn"
                :data="row.detail"
              >
                <!-- 允许空模板 -->
                <template v-slot:f_isnullable="{ row }">
                  <el-tag
                    effect="dark"
                    :type="row.f_isnullable === '1' ? 'success' : 'info'"
                    >{{ row.f_isnullable === "1" ? "是" : "否" }}</el-tag
                  >
                </template>
                <!-- 主键模板 -->
                <template v-slot:f_key="{ row }">
                  <el-tag
                    effect="dark"
                    :type="row.f_key === '1' ? 'success' : 'info'"
                    >{{ row.f_key === "1" ? "是" : "否" }}</el-tag
                  >
                </template>
              </vxe-grid>
            </template>
          </vxe-grid>
        </div>
        <!-- 信息配置 -->
        <div v-show="active === 1" class="step_div">
            <el-alert 
                title="信息配置" 
                description="配置物理文件生成路径，目录层级对应模块与应用域" 
                :closable="false" type="info" show-icon effect="dark">
            </el-alert>
            <vxe-form
                ref="firstForm"
                title-width="100"
                title-align="right"
                :data="config"
                :rules="rules"
                span="8"
            >
                <vxe-form-item title="模块" field="Module">
                  <rayd-select options="ModuleSelect" v-model="config.Module"></rayd-select>
                </vxe-form-item>
                <vxe-form-item title="应用域" field="AppDomain">
                  <el-input v-model="config.AppDomain" placeholder="请输入" clearable></el-input>
                </vxe-form-item>
            </vxe-form>
        </div>
        <!-- 代码预览 -->
        <div v-show="active === 2" class="step_div">
          <coder v-model="previewCode" language="Java"/>
        </div>
      </el-scrollbar>
    </template>
    <template slot="footer">
      <el-button type="primary" @click="previous" :disabled="active === 0">上一步</el-button>
      <el-button type="primary" @click="next">{{this.active === 2 ? `完成`:`下一步`}}</el-button>
      <el-button type="warning" v-form-validate="generate" v-if="this.active === 1">直接生成</el-button>
    </template>
  </vxe-modal>
</template>

<script>
import { DatabaseTable, CodeGenerator } from "@/api";
import coder from "@/components/Codemirror";
export default {
  props: {},
  components: { coder },
  data() {
    return {
      //表单可见
      formVisible: true,
      //表单加载中
      formLoading: false,
      //存放表单ref数组
      formArr: ["firstForm"],
      //表单实体
      config: {
          TableNames: [],
          FieldList: [],
          IsTree: false,
          IsPage: false,
          Area: '',
          Module: '',
          AppDomain: '',
          FontSrcPath:'',
          ModuleEntity: {}
      },
      //表单验证规则（规则键必须和表单键一致）
      rules: {
          Module: [{ required: true, message: "请选择模块!" }],
          AppDomain: [{ required: true, message: "请输入应用域!" }],
      },
      /* vxe-grid */
      filterName: "", //查询实体
      tableData: [], //表格实体
      //工具栏配置
      tableToolbar: {
        refresh: { 
          query : ()=> {
            this.filterName = ''; //清空条件
            this.loadTables();
          }
        },
        zoom: true,
        custom: true,
      },
      //列配置
      tableColumn: [
        {
          type: "checkbox",
          width: 50,
        },
        {
          type: "expand",
          width: 50,
          slots: { content: "subTable" },
        },
        {
          type: "seq",
          title: "序号",
          width: 80,
          align: "left",
        },
        { type: "html", field: "name", title: "表名", sortable: true },
        { type: "html", field: "sumrows", title: "记录条数", sortable: true },
        { type: "html", field: "data", title: "使用大小", sortable: true },
        {
          type: "html",
          field: "index_size",
          title: "索引使用大小",
          sortable: true,
        },
        { type: "html", field: "tdescription", title: "说明", sortable: true },
      ],
      //子列配置
      subTableColumn: [
        {
          type: "seq",
          title: "序号",
          width: 80,
          align: "left",
        },
        { field: "f_column", title: "字段名", sortable: true, align: "left" },
        { field: "f_datatype", title: "数据类型", sortable: true },
        { field: "f_length", title: "长度", sortable: true },
        {
          field: "f_isnullable",
          title: "允许空",
          sortable: true,
          slots: { default: "f_isnullable" },
        },
        { field: "f_identity", title: "标识", sortable: true },
        {
          field: "f_key",
          title: "主键",
          sortable: true,
          slots: { default: "f_key" },
        },
        { field: "f_defaults", title: "默认值", sortable: true },
        {
          field: "f_remark",
          title: "说明",
          sortable: true,
          width: 200,
          align: "left",
        },
      ],
      /* 实体数据 */
      active: 0,
      moduleList: this.util.getDataItemList('ModuleSelect'),
      previewCode: "",
    };
  },
  created() {
    //初始化
    this.init();
  },
  methods: {
    //初始化
    init() {
      this.formLoading = true;
      Promise.all([]).then(res=>{
        this.loadTables();
      })
    },
    //加载数据表
    loadTables() {
      this.formLoading = true;
      return DatabaseTable.GetList({queryjson:JSON.stringify({QueryInfo:this.filterName})}).then((res) => {
        this.tableData = res;
        this.formLoading = false;
      });
    },
    //行展开回调
    expanded({ row }) {
      return DatabaseTable.GetFieldList(row.name).then((res) => {
        row.detail = res;
      });
    },
    //上一步
    previous(){
        const currentStage = this.active;
        if (currentStage === 0){
            return;
        }else{
            this.active--;
        }
    },
    //下一步
    next(){
        const currentStage = this.active;
        if (currentStage === 0){
            // 获取表名
            let tables = this.$refs['mainTable'].getCheckboxRecords();
            if(this.util.validateNull(tables)){
              this.$message({ message: '请选择数据表', type: "warning"});
              return;
            }
            let tableNames = [];
              tables.forEach(o => {
              tableNames.push(o.name);
            });
            // 形成配置信息
            this.config.TableNames = tableNames;
            this.config.AppDomain = tableNames[0];
            this.active++;
        }else if(currentStage === 1){
            this.util.formValidate(()=>{
                    // 验证通过
                    this.formLoading = true;
                    // 获取预览代码
                    CodeGenerator.PreviewEntityCode(this.config).then(res=>{
                      this.previewCode = res;
                      this.formLoading = false;
                      this.active++;
                    })
            })
        }else if(currentStage === 2){
            this.generate();
        }
    },
    //生成代码
    generate(){
          //验证通过，提交生成代码
          CodeGenerator.GenerateEntityCode(this.config).then(res=>{
            this.$emit("close");
          })
    }
  },
};
</script>

<style lang="less" scoped>
.step_div{
    margin-top:10px
}
</style>
